package com.kye.express.business.login;

import android.app.Dialog;
import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxCompoundButton;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.complete_information.CompleteInformationActivity;
import com.kye.express.business.web.KyeWebActivity;
import com.kye.express.databinding.ActivityLoginBinding;
import com.kye.express.databinding.DialogImageVerificationCodeBinding;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.user.User;
import com.tuo.customview.VerificationCodeView;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function3;

public class LoginActivity extends BaseAppCompatActivity implements LoginContract.LoginView {

    private ActivityLoginBinding mBinding;
    private LoginContract.LoginPresenter mPresenter;
    private DialogImageVerificationCodeBinding mDialogImageVerificationCodeBinding;
    private MaterialDialog mVerificationCodeDialog;
    private Dialog mDialog;

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, LoginActivity.class));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_login);

        initEvent();
        initData();
    }

    private void initEvent() {
        setSupportActionBar(mBinding.toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        mBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        Observable<CharSequence> phoneChange = RxTextView.textChanges(mBinding.editTextLoginPhone).cache();
        Observable<CharSequence> verificationCodeChange = RxTextView.textChanges(mBinding.editTextLoginVerificationCode).cache();
        Observable<Boolean> protocolCheckedChanges = RxCompoundButton.checkedChanges(mBinding.checkBoxLoginProtocol).cache();

        Observable.combineLatest(phoneChange, protocolCheckedChanges, new BiFunction<CharSequence, Boolean, Boolean>() {
            @Override
            public Boolean apply(CharSequence charSequence, Boolean aBoolean) throws Exception {
                return !TextUtils.isEmpty(charSequence.toString().trim());
            }
        })
                .compose(this.<Boolean>bindToLifecycleDestroy())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.setVerificationCodeEnabled(aBoolean);
                    }
                });

        Observable.combineLatest(phoneChange, verificationCodeChange, protocolCheckedChanges, new Function3<CharSequence, CharSequence, Boolean, Boolean>() {
            @Override
            public Boolean apply(CharSequence charSequence, CharSequence charSequence2, Boolean aBoolean) throws Exception {
                return charSequence.length() >= 11 && !TextUtils.isEmpty(charSequence2.toString().trim()) && aBoolean;
            }
        })
                .compose(this.<Boolean>bindToLifecycleDestroy())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        mBinding.buttonLoginLogin.setEnabled(aBoolean);
                    }
                });

        RxView.clicks(mBinding.buttonLoginGetVerificationCode)
                .map(new Function<Object, Object>() {
                    @Override
                    public Object apply(Object o) throws Exception {
                        final String phone = mBinding.editTextLoginPhone.getText().toString().trim();
                        if (!phone.startsWith("1") || phone.length() < 11) {
                            return new IllegalArgumentException();
                        }
                        return o;
                    }
                })
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof IllegalArgumentException) {
                            ToastManager.show(LoginActivity.this, R.string.login_place_input_phone);
                            return;
                        }

                        mPresenter.getSmsVerificationCode(mBinding.editTextLoginPhone.getText().toString().trim(), null);
                    }
                });

        RxView.clicks(mBinding.buttonLoginLogin)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.loginOrRegister(
                                mBinding.editTextLoginPhone.getText().toString().trim(),
                                mBinding.editTextLoginVerificationCode.getText().toString().trim()
                        );
                    }
                });

        RxView.clicks(mBinding.textViewProtocol)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        KyeWebActivity.startActivity(LoginActivity.this, "https://res.ky-express.com/activity/delegate.html", "跨越服务协议", false);
                    }
                });
    }

    private void countDown(final Long seconds) {
        Flowable.interval(0, 1, TimeUnit.SECONDS)
                .take(seconds)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return seconds - aLong;
                    }
                })
                .compose(getProvider().<Long>bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long s) throws Exception {
                        mBinding.setVerificationCodeTimer(s);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mBinding.setVerificationCodeTimer(null);
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        mBinding.setVerificationCodeTimer(null);
                    }
                });
    }

    private void initData() {
        mPresenter = new LoginContract.LoginPresenter();
        mPresenter.bind(this);
    }

    @Override
    public void onCountDown(Long seconds) {
        countDown(seconds);
    }

    @Override
    public void onCompleteInformation(User user) {
        CompleteInformationActivity.startActivity(this, user);
        finish();
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public void onLoading() {
        mDialog = KyeProgressDialog.show(this, mDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mDialog);
    }

    @Override
    public void onGotSmsVerificationCode() {
        if (mVerificationCodeDialog != null && mVerificationCodeDialog.isShowing()) {
            mVerificationCodeDialog.dismiss();
        }

        if (mDialogImageVerificationCodeBinding != null) {
            mDialogImageVerificationCodeBinding.verificationCodeView.clearInputContent();
        }

        ToastManager.show(this, R.string.login_message_verification_code_sent_successfully);

        countDown(GET_VERIFICATION_CODE_INTERVAL);
    }

    @Override
    public void onError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onLogined(User user) {
        ToastManager.show(this, R.string.login_login_successfully);
        finish();
    }

    @Override
    public void onError(String msg) {
        if (mDialogImageVerificationCodeBinding != null) {
            mDialogImageVerificationCodeBinding.verificationCodeView.clearInputContent();
        }

        ToastManager.show(this, msg);
    }

    @Override
    public void onGotImageVerificationCode(byte[] bytes) {
        if (mVerificationCodeDialog == null) {
            View inflate = LayoutInflater.from(this).inflate(R.layout.dialog_image_verification_code, null);
            mDialogImageVerificationCodeBinding = DialogImageVerificationCodeBinding.bind(inflate);

            RxView.clicks(mDialogImageVerificationCodeBinding.imageViewVerificationCode)
                    .compose(new DebounceObservableTransformer<>())
                    .compose(getProvider().bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                    .subscribe(new Consumer<Object>() {
                        @Override
                        public void accept(Object o) throws Exception {
                            mPresenter.getImageVerificationCode(mBinding.editTextLoginPhone.getText().toString().trim());
                        }
                    });

            mDialogImageVerificationCodeBinding.verificationCodeView.setInputCompleteListener(new VerificationCodeView.InputCompleteListener() {
                @Override
                public void inputComplete() {
                    if (mDialogImageVerificationCodeBinding.verificationCodeView.getInputContent().length() >= 4) {
                        mPresenter.getSmsVerificationCode(
                                mBinding.editTextLoginPhone.getText().toString().trim(),
                                mDialogImageVerificationCodeBinding.verificationCodeView.getInputContent()
                        );
                    }
                }

                @Override
                public void deleteContent() {}
            });

            mVerificationCodeDialog = new MaterialDialog.Builder(this)
                    .title(R.string.login_please_enter_the_image_verification_code)
                    .customView(mDialogImageVerificationCodeBinding.getRoot(), false)
                    .negativeText(R.string.common_cancel)
                    .build();
        }

        Glide.with(LoginActivity.this)
                .load(bytes)
                .into(mDialogImageVerificationCodeBinding.imageViewVerificationCode);

        mVerificationCodeDialog.show();
    }
}
